package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.MqConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.MultiDelayMessage;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * @author 衷岚
 * @version 1.0
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO add(OrdersSubmitDTO ordersSubmitDTO) {
        User user = userMapper.findById(BaseContext.getCurrentId());

        //数据校验
        //判断地址簿是否为空
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        if (addressBook == null) {
            throw new AddressBookBusinessException("地址簿不能为空");
        }
        //判断购物车是否为空
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(cart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException("购物车不能为空");
        }
        //插入订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setStatus(1);
        orders.setPayStatus(0);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orderMapper.insert(orders);

        //插入订单明细表
        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
        for (ShoppingCart cart1 :list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(cart1, orderDetail);

            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车
        if(list!=null && list.size()>0) {
            shoppingCartMapper.deleteAll(BaseContext.getCurrentId());
        }

        //返回vo
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());

        /**
         * rabbitmq 延迟队列
         *
         * 定时处理超时订单 优化
         *
         * 向处理订单状态的延时交换机发送消息
         */
        try {
            MultiDelayMessage<Long> delayMessage = MultiDelayMessage.of(orders.getId(), 10000, 15000,30000,60000,480000);//......一共15分钟，订单等待支付时间分片
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,MqConstant.DELAY_ORDER_ROUTING_KEY,delayMessage, new MessagePostProcessor() {

                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay((delayMessage.removeNextDelay()));
                    return message;
                }
            });
        } catch (RuntimeException e) {
            log.info("检测订单状态异常...");
        }

        return orderSubmitVO;

    }


    @Override
    public void update(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = new Orders();

        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setPayMethod(ordersPaymentDTO.getPayMethod());

        orders.setPayStatus(1);
        orders.setStatus(2);
        orderMapper.update(orders);
    }

    @Override
    public Orders getByNumber(String orderNumber) {
        Orders order = orderMapper.getByNumber(orderNumber);
        return order;
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {

        Orders order = orderMapper.getById(id);

        //校验订单是否存在
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //通过websocket向商家客户端推送信息
        //type orderId content

        HashMap<String, Object> map = new HashMap<>();
        map.put("type", 2);//1表示来单提醒， 2表示客户催单
        map.put("orderId",id);
        map.put("content","订单号："+order.getNumber());
        //转为jason字符串
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }


    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    @Transactional
    public void repetition(Long id) {
        //自动加购
        //查找之前订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //判断订单是否存在
        if(orderDetailList == null || orderDetailList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //封装给购物车实体类
        List<ShoppingCart> cartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            orderDetail.setId(null);
            ShoppingCart cart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail, cart);
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
//            cart.setId(null);
            //加入购物车
            cartList.add(cart);
        }

        //清空购物车
        ShoppingCart cartt = new ShoppingCart();
        cartt.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(cartt);

        if(list!=null && list.size()>0) {
            shoppingCartMapper.deleteAll(BaseContext.getCurrentId());
        }
        //批量加购
        shoppingCartMapper.insertBatch(cartList);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);

    }

    /**
     * 条件分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {

        //分页插件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> pg = orderMapper.pageQuery4Admin(ordersPageQueryDTO);
        return new PageResult(pg.getTotal(), pg.getResult());


    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);


    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        //退款
//        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setPayStatus(Orders.REFUND);
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        //设置订单状态为已完成
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 各个状态订单的数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        int toBeConfirmed = orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        int confirmed = orderMapper.countByStatus(Orders.CONFIRMED);
        int deliveryInProgress = orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);
        int completed = orderMapper.countByStatus(Orders.COMPLETED);
        int cancelled = orderMapper.countByStatus(Orders.CANCELLED);


        return new OrderStatisticsVO(toBeConfirmed,confirmed,deliveryInProgress,completed,cancelled);
    }
}
